#!/usr/bin/perl
#
# (C) Copyright 2010- Hewlett-Packard Development Company, L.P.
# 
#  $Id: instance_template 18003 2012-05-10 07:14:33Z cheng-xin.cai@hp.com $
#

use strict;
use 5.008000;
use warnings;
use POSIX;
use Getopt::Long; 
use File::Basename;
use Sys::Hostname;

use lib '/opt/hp/nv/lib/perl';
use config ':all';
use instance ':all';

# possible error returns
use constant {
    OK => 0,
    WARN => 1,
    CRITICAL => 2,
    UNKNOWN => 3,
};

# Global variables

# common global variables
my $proceed=1;
my $done=0;

my $myscriptname = "remoldinstance";
my $revision = '$Revision: 18003 $';
$revision =~ s/\$//g;

# script specific globals
my $IMAGEDIR = "/cm/images";
my $pdsh_cmd = "/usr/bin/pdsh";
my $sealog_dir = "/home/sealog";
my $pm_dir = "/home/pmcontext";

my $gv_squser = $ENV{USER};
my @gv_locations;
# command line options
my %gv_opts;

# DO NOT DELETE/DO NOT MODIFY
#
# This sub calls module routine to log informational message to log file
# after first prepending program name; timestamp will be added in
# Perl module
#
sub log_msg
{
    my $message = shift;
    my $infomessage;

    $infomessage = basename($0) . ": INFO: ". $message . "\n";
    instance_log_event($infomessage);
}

# DO NOT DELETE/DO NOT MODIFY
#
# This sub calls module routine to log warning message to log file
# after first prepending program name and Warning label; a timestamp 
# will be added in Perl module
#
sub log_warn
{
    my $message = shift;
    my $warnmessage;

    $warnmessage = basename($0) . ": WARNING: ". $message . "\n";
    instance_log_event($warnmessage);

}

# DO NOT DELETE/DO NOT MODIFY
#
# This sub calls module routine to log error message to log file
# after first prepending program name; timestamp will be added in
# Perl module; the program will then exit
#
sub logerr_n_die
{
    my $message = shift;
    my $errormessage;

    $errormessage = basename($0) . ": ERROR: ". $message . "\n";
    print STDERR $errormessage;
    
    instance_log_event($errormessage);
    exit(CRITICAL);

}

# CHANGE FOR YOUR NEEDS
#
# This sub checks for any requirements that must be met before 
# the configuration is performed.
#
sub pre_req_check
{
    log_msg("Source node is: " . hostname());
    logerr_n_die("This script cannot be run as root!") 
        if ($gv_squser eq "root");

    logerr_n_die("Not a Bright Cluster") if (cluster_type() != config::BRIGHT);

    log_msg("Remove Instance executed by: $gv_squser");

    if ($gv_opts{all}) {
        # whether use pdsh -a or pdsh -w $nodes? How about there are some 
        # instances for the user outside of noderange?
        my $dirs = run_cmd("$pdsh_cmd -a ls /opt/hp/$gv_squser| awk '{prin t \$2}'");
        my %tmpHash = map {"/opt/hp/$gv_squser/$_" => 1}, split('\n', $dirs);

        @gv_locations = keys %tmpHash;
    }
    else {
        @gv_locations = split(/,/, join(',', @{$gv_opts{locations}}));

        for my $dir (@gv_locations) {
            log_msg("Instance Directory: $dir");

            my $pdir = dirname($dir);
            if ($pdir ne "/opt/hp/$gv_squser") {
                logerr_n_die("Directory path $pdir is an invalid instance path name");
            }

            if (! -d $dir) {
                log_warn("Directory path $dir either does not exist on this node");
            }
        }
    }

    return(OK);
}

# CHANGE FOR YOUR NEEDS
#
# This sub verifies that the work done is complete and in such a state 
# that it is ready for the next step to be done
#
sub post_check
{
    return(OK);
}

sub run_cmd($)
{
    my $cmd = shift;
    if ($gv_opts{dryrun}) {
        print STDOUT $cmd . "\n";
        $? = 0;
        return "";
    }
    else {
        chomp (my $outputs = `$cmd`);

        if (WIFEXITED($?) && (WEXITSTATUS($?) != 0)) {
            logerr_n_die("An error occured when execute the cmd $cmd:"
                     . WEXITSTATUS($?));
        }
        return $outputs;
    }
}

sub remove_instance($)
{
    my $dir = shift;

    run_cmd("rm -rf $dir");

    my @images = get_image_names();
    for my $image (@images) {
        run_cmd("rm -rf $IMAGEDIR/$image/$dir");     
    }

    my $nodes = get_instance_nodelist($gv_squser);

    run_cmd("$pdsh_cmd -w $nodes /bin/rm -rf $dir");

    cm_UpdateProvisioners(); # This only to sync the backup headnode

    my $tmp_dir = $dir;
    $tmp_dir =~ s/\//_/g;
    run_cmd("rm -rf $sealog_dir/$gv_squser/$tmp_dir");
    run_cmd("rm -rf $pm_dir/$gv_squser/$tmp_dir");
    run_cmd("rm -rf /home/$gv_squser/context");

    cm_RemoveExcludeList("$dir/");
}

# CHANGE FOR YOUR NEEDS
#
# This sub verifies that the work done is complete and in such a state 
# that it is ready for the next step to be done
#
sub perform_config
{
    # CHANGE FOR YOUR NEEDS
    # 
    # do your configuration processing here!
    # 
	
    for my $dir (@gv_locations) {
        remove_instance($dir);
    }

    return(OK);
}

# CHANGE FOR YOUR NEEDS
# 	define what your script does.
#
# usage
#
sub usage
{
print <<"EOF";

This script will remove any old instance .

$myscriptname --help

   -all|a           remove all the existing instance
   -locations|l     Enter the fully qualified path location(s) of the SQL instance to be removed

   Example: $myscriptname -l /opt/hp/squser1/SQFAAA/ 
   Will run the tool in remove mode on /opt/hp/squser1/SQFAAA/ directory
   
   Example: $myscriptname -l /opt/hp/squser1/SQFAAA/,/opt/hp/squser1/SQFBBB/
   Will remove multiple directories in remove mode for /opt/hp/squser1/SQFAAA/,/opt/hp/squser1/SQFBBB/

   -h Help
   
EOF

exit(UNKNOWN);
}

### Main ###

# DO NOT DELETE/DO NOT MODIFY
#
# Do not delete any of the following subroutine calls.  
# You can add more code to perform_config
#

# The only option supported right now is help
# generate usage output for anything else.
&GetOptions( \%gv_opts,
             "dryrun|test",
             "all|a",
             "locations|l=s@",
             "help"=> \&usage) or usage(); 

log_msg("Starting script: revision number $revision");

pre_req_check;

perform_config;

post_check;

# Return success 
exit(OK);



 




